package controllers

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"wallet/helpers"
	"wallet/models"
)

func LoginPost(c *gin.Context) {
	session := sessions.Default(c)
	uname := c.PostForm("uname")
	pwd := c.PostForm("pwd")

	if len(uname) == 0 || len(pwd) == 0 {
		c.JSON(200, gin.H{
			"succeed": false,
			"message": "uname or pwd missed.",
		})
	} else {
		user := models.Login(uname)
		if user != nil && user.ID > 0 {
			encrytPwd := helpers.Md5(pwd)
			if user.Password == encrytPwd {
				session.Clear()
				session.Set(SESSION_USER, user)
				session.Save()
				c.JSON(200, gin.H{
					"succeed": true,
					"message": "login succeessful.",
				})
			} else {
				c.JSON(200, gin.H{
					"succeed": false,
					"message": "error password.",
				})
			}
		} else {
			c.JSON(200, gin.H{
				"succeed": false,
				"message": "account not exist.",
			})
		}
	}
}

func Logout(c *gin.Context) {
	s := sessions.Default(c)
	s.Clear()
	s.Save()
	c.Redirect(http.StatusSeeOther, "/")
}

func SignupPost(c *gin.Context) {
	telephone := c.PostForm("telephone")
	email := c.PostForm("email")
	pwd := c.PostForm("pwd")
	if len(telephone) == 0 || len(email) == 0 || len(pwd) == 0 {
		c.JSON(200, gin.H{
			"succeed": "false",
			"message": "miss parameter.",
		})
		return
	}
	encrytPwd := helpers.Md5(pwd)
	if models.InsertUser(telephone, email, encrytPwd) {
		c.JSON(200, gin.H{
			"succeed": "true",
			"message": "add user succeed.",
			"data":    nil,
		})
	} else {
		c.JSON(200, gin.H{
			"succeed": "false",
			"message": "add user failed.",
		})
	}
}
